Write a function that accepts a string. The function should capitalize the first letter of each word in the string then return the capitalized string.
capitalize('a short sentence') --> 'A Short Sentence'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'
Two solutions
1. Array of strings
String.prototype.slice()
, String.prototype.toUpperCase()
, Array.prototype.join()
slice(" ")
and join(" ")
with a space in them2. Array of characters
function capitalize(str) {
let words = [];
for (let word of str.split(" ")){ // split with a space
words.push(word[0].toUpperCase() + word.slice(1));
}
return words.join(" "); // join with a space
}
function capitalize(str) {
let result = "";
for (let i=0; i<str.length;i++){
if (str[i-1] === " " || i === 0){
result += str[i].toUpperCase(); //use +=
} else {
result += str[i];
}
}
return result;
}
capitalize('a short sentence')
capitalize('a lazy fox')
capitalize('look, it is working!')